# LocalStack Resource Provider Scaffolding v2
from __future__ import annotations

import json
from pathlib import Path
from typing import Optional, TypedDict

import localstack.services.cloudformation.provider_utils as util
from localstack.services.cloudformation.resource_provider import (
    OperationStatus,
    ProgressEvent,
    ResourceProvider,
    ResourceRequest,
)
from localstack.utils.json import canonical_json
from localstack.utils.strings import md5


class S3BucketPolicyProperties(TypedDict):
    Bucket: Optional[str]
    PolicyDocument: Optional[dict]
    Id: Optional[str]


REPEATED_INVOCATION = "repeated_invocation"


class S3BucketPolicyProvider(ResourceProvider[S3BucketPolicyProperties]):
    TYPE = "AWS::S3::BucketPolicy"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

    def create(
        self,
        request: ResourceRequest[S3BucketPolicyProperties],
    ) -> ProgressEvent[S3BucketPolicyProperties]:
        """
        Create a new resource.

        Primary identifier fields:
          - /properties/Id

        Required properties:
          - Bucket
          - PolicyDocument

        Create-only properties:
          - /properties/Bucket

        Read-only properties:
          - /properties/Id



        """
        model = request.desired_state
        s3 = request.aws_client_factory.s3

        s3.put_bucket_policy(Bucket=model["Bucket"], Policy=json.dumps(model["PolicyDocument"]))
        model["Id"] = md5(canonical_json(model["PolicyDocument"]))

        return ProgressEvent(
            status=OperationStatus.SUCCESS,
            resource_model=model,
            custom_context=request.custom_context,
        )

    def read(
        self,
        request: ResourceRequest[S3BucketPolicyProperties],
    ) -> ProgressEvent[S3BucketPolicyProperties]:
        """
        Fetch resource information


        """
        raise NotImplementedError

    def delete(
        self,
        request: ResourceRequest[S3BucketPolicyProperties],
    ) -> ProgressEvent[S3BucketPolicyProperties]:
        """
        Delete a resource


        """
        model = request.desired_state
        s3 = request.aws_client_factory.s3

        try:
            s3.delete_bucket_policy(Bucket=model["Bucket"])
        except s3.exceptions.NoSuchBucket:
            pass

        return ProgressEvent(
            status=OperationStatus.SUCCESS,
            resource_model=model,
            custom_context=request.custom_context,
        )

    def update(
        self,
        request: ResourceRequest[S3BucketPolicyProperties],
    ) -> ProgressEvent[S3BucketPolicyProperties]:
        """
        Update a resource


        """
        raise NotImplementedError
